import 'package:core/ui/base/base_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

class CoreProvider<T extends ChangeNotifier> extends StatefulWidget {
  final T model;
  final ValueWidgetBuilder<T> builder;
  final bool wantKeepAlive;
  final SystemUiOverlayStyle? style;

  const CoreProvider({
    super.key,
    required this.model,
    required this.builder,
    this.wantKeepAlive = false,
    this.style,
  });

  @override
  State<CoreProvider<T>> createState() => _CoreProviderState<T>();
}

class _CoreProviderState<T extends ChangeNotifier> extends State<CoreProvider<T>> with AutomaticKeepAliveClientMixin {

  late T model;

  @override
  void initState() {
    model = widget.model;
    if(model is BaseViewModel) (model as BaseViewModel).initState();
    super.initState();
  }

  @override
  void dispose() {
    if(model is BaseViewModel) (model as BaseViewModel).dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.wantKeepAlive) super.build(context);
    if(model is BaseViewModel) (model as BaseViewModel).setBuildContext(context);
    Widget child;
    child = ChangeNotifierProvider<T>.value(
      value: model,
      child: Consumer<T>(
        builder: widget.builder,
      ),
    );
    if (widget.style != null) {
      child = AnnotatedRegion<SystemUiOverlayStyle>(
        value: widget.style!,
        child: child,
      );
    }
    return child;
  }

  @override
  bool get wantKeepAlive => widget.wantKeepAlive ?? false;
}
